package org.lease.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import org.lease.common.constant.CaptchaConstant;
import org.lease.common.constant.RedisConstant;
import org.lease.common.exception.BizException;
import org.lease.common.holder.LoginUser;
import org.lease.common.holder.LoginUserHolder;
import org.lease.common.utils.JWTUtil;
import org.lease.model.dto.CaptchaDTO;
import org.lease.model.dto.LoginDTO;
import org.lease.model.entity.SystemUser;
import org.lease.model.enums.BaseStatus;
import org.lease.service.LoginService;
import org.lease.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserService systemUserService;


    // 获取图形验证码
    @Override
    public CaptchaDTO getCaptcha() {
        // 生成图形验证码
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(CaptchaConstant.WIDTH, CaptchaConstant.HEIGHT, CaptchaConstant.CODE_COUNT);
        String code = gifCaptcha.getCode();
        String imageBase64Data = gifCaptcha.getImageBase64Data();
        // 缓存到 Redis
        String uuid = UUID.randomUUID().toString();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + uuid;
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.HOURS);
        // 返回数据
        return new CaptchaDTO(uuid, imageBase64Data);
    }

    // 用户登录
    @Override
    public String login(LoginDTO loginDTO) {
        // 校验验证码
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + loginDTO.getCaptchaKey();
        String code = stringRedisTemplate.opsForValue().get(key);
        if (code == null) {
            throw new BizException("验证码已过期");
        }
        if (!loginDTO.getCaptchaCode().equalsIgnoreCase(code)) {
            throw new BizException("验证码错误");
        }
        // 校验用户名和密码
        SystemUser user = systemUserService.getByUsername(loginDTO.getUsername());
        String password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (user == null || !Objects.equals(user.getPassword(), password)) {
            throw new BizException("用户名或密码错误");
        }
        // 校验账号状态
        if (user.getStatus() == BaseStatus.DISABLE) {
            throw new BizException("账户已被锁定，请联系管理员");
        }
        // 生成 Token 并返回
        return JWTUtil.createToken(user.getId(), user.getUsername());
    }

    // 获取用户信息
    @Override
    public SystemUser getUserInfo() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        Long userId = loginUser.getUserId();
        return systemUserService.getById(userId);
    }


}

